package com.daichi.security;

import cn.hutool.core.util.StrUtil;
import com.daichi.entity.SysUser;
import com.daichi.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    private final SysUserService sysUserService;

    @Autowired
    public UserDetailServiceImpl(SysUserService sysUserService) {
        this.sysUserService = sysUserService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUser sysUser = sysUserService.getUserByName(username);

        if (sysUser == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }

        return new AccountUser(sysUser.getId(), sysUser.getUsername(), sysUser.getPassword(), getUserAuthority(sysUser.getId()));
    }

    public List<GrantedAuthority> getUserAuthority(Long userId) {

        SysUser sysUser = sysUserService.getById(userId);

        if (sysUser == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }

        return getUserAuthority(sysUser.getUsername());
    }

    public List<GrantedAuthority> getUserAuthority(String username) {

        String authority = sysUserService.getUserAuthorityInfo(username);

        if (StrUtil.isEmpty(authority)) {
            return null;
        }

        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }
}
